package cn.cscb.mms.server.handler;

import cn.cscb.mms.common.exception.BaseException;
import cn.cscb.mms.common.exception.SomeBusinessException;
import cn.cscb.mms.common.result.Result;
import cn.cscb.mms.common.result.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author Gao Yipeng
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获默认业务异常
     *
     * @param ex 异常类
     * @return 统一响应类
     */
    @ExceptionHandler(BaseException.class)
    public Result<Void> exceptionHandler(BaseException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(SomeBusinessException.class)
    public Result<Void> handleSomeBusinessException(SomeBusinessException ex) {
        log.error("测试用异常信息：{}", ex.getMessage());
        return Result.error(ResultEnum.COMMON_FAILED.getCode(), ex.getMessage());
    }

    /**
     * 处理参数异常
     * @param ex 参数异常类
     * @return 异常信息
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<Void> handleArgumentException(IllegalArgumentException ex) {
        log.error(ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 系统其他异常
     * @param ex 异常类
     * @return 异常信息
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleOtherException(Exception ex) {
        log.error(ex.getMessage());
        ex.printStackTrace();
        return Result.error("系统繁忙");
    }
}
